<template>
  <div class="water-list" ref="waterList" :style="{ padding: gap + 'px' }">
    <div
      class="r_counlm"
      v-for="(item, index) in list"
      :key="item.id ? item.id : index"
      :style="RcounlmStyle(item, index)"
    >
      <!-- <div class=""> -->
      <template v-for="(it, idx) in item.dataList" :key="it.id ? it.id : idx">
        <slot :row="it"></slot>
      </template>
      <!-- </div> -->
    </div>
  </div>
</template>

<script>
let debounce = null;
export default {
  name: "WaterfallFlowComponent",
  props: {
    dataList: {
      type: Array,
      default: () => [],
    },
    // 间隔
    gap: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {
      observer: null,
      column: 0,
      list: [],
      RcounlmConfig: {
        width: 200,
      },
    };
  },
  created() {},
  mounted() {
    this.observer = new ResizeObserver((entries) => {
      const rect = entries[0].contentRect;
      console.log("🚀 ~ this.observer=newResizeObserver ~ rect:", rect);
      if (rect.width > 1500) {
        this.column = 5;
        this.initData();
      } else if (rect.width > 1200) {
        this.column = 4;
        this.initData();
      } else if (rect.width > 900) {
        this.column = 3;
        this.initData();
      } else {
        this.column = 2;
        this.initData();
      }
      if (debounce) clearTimeout(debounce);
      // 防抖调用
      debounce = setTimeout(() => {
        this.getRcounlmConfig();
      }, 200);
    });
    this.observer.observe(document.querySelector(".water-list"));
  },
  methods: {
    initData() {
      this.list = new Array(this.column).fill(0).map((item, index) => {
        return {
          id: index + item + new Date().getTime(),
          dataList: [],
        };
      });
      let columnIndex = 0;
      this.dataList.forEach((item, index) => {
        if (index % this.column === 0) {
          columnIndex = 0;
        }
        this.list[columnIndex].dataList.push(item);
        columnIndex++;
      });
      console.log("🚀 ~ this.list=newArray ~ this.list:", this.list);
    },
    getRcounlmConfig() {
      this.RcounlmConfig.width =
        (document.querySelector(".water-list").offsetWidth -
          (this.column + 1) * this.gap) /
        this.column;
    },
    RcounlmStyle(item, index) {
      const _style = {
        width: this.RcounlmConfig.width + "px",
      };
      if (index != this.list.length - 1) {
        _style.marginRight = this.gap + "px";
      }
      return _style;
    },
  },
  computed: {},
  beforeDestroy() {
    this.observer.disconnect();
  },
};
</script>
<style scoped lang='less'>
.water-list {
  display: flex;
  flex-wrap: wrap;
  width: 100%;

  .item {
    width: 100%;
    margin-bottom: 10px;
  }
}
</style>
